package org.aceor.mddal.common.sqlparser.result.context;


import com.google.common.base.Objects;
import com.google.common.base.Strings;
import org.aceor.mddal.common.sharding.ShardingFunction;

import java.text.MessageFormat;

/**
 * Created by lxue on 16/4/12.
 */
public class ShardingContext {

    public String logicTableName;
    private ShardingType shardingType;
    public String tbShardingColumn;
    public String dbShardingColumn;
    public ShardingFunction dbShardingFunction;
    public ShardingFunction tbShardingFunction;
    public MessageFormat dbNameMessageFormat;
    public MessageFormat tbNameMessageFormat;

    public enum ShardingType {
        NO_SHARDING, JUST_TB_SHARDING, JUST_DB_SHARDING, TB_DB_BOTH_SHARDING;
    }

    public ShardingType getShardingType() {
        if (Strings.isNullOrEmpty(tbShardingColumn)
                && Strings.isNullOrEmpty(dbShardingColumn)) {
            return ShardingType.NO_SHARDING;
        } else if (!Strings.isNullOrEmpty(tbShardingColumn)
                && !Strings.isNullOrEmpty(dbShardingColumn)) {
            return ShardingType.TB_DB_BOTH_SHARDING;
        } else if (Strings.isNullOrEmpty(tbShardingColumn)) {
            return ShardingType.JUST_DB_SHARDING;
        } else if (Strings.isNullOrEmpty(dbShardingColumn)) {
            return ShardingType.JUST_TB_SHARDING;
        } else {
            //不会走到这里
            throw new IllegalArgumentException("未找到对应sharding类型");
        }
    }

    public String convertDbName(String value) {
        if (null == dbNameMessageFormat) {
            throw new IllegalArgumentException();
        }
        if (Strings.isNullOrEmpty(value)) {
            throw new NullPointerException();
        }
        return dbNameMessageFormat.format(new String[]{value});
    }

    public String convertTbName(String value) {
        if (null == tbNameMessageFormat) {
            throw new IllegalArgumentException();
        }
        if (Strings.isNullOrEmpty(value)) {
            throw new NullPointerException();
        }
        return tbNameMessageFormat.format(new String[]{value});
    }

    public String convertDbName(Integer value) {
        return convertDbName(String.valueOf(value));
    }

    public String convertTbName(Integer value) {
        return convertTbName(String.valueOf(value));
    }

    public String convertDbName(Long value) {
        return convertDbName(String.valueOf(value));
    }

    public String convertTbName(Long value) {
        return convertTbName(String.valueOf(value));
    }
    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("logicTableName", logicTableName)
                .add("shardingType", shardingType)
                .add("tbShardingColumn", tbShardingColumn)
                .add("dbShardingColumn", dbShardingColumn)
                .toString();
    }
}
